package main

import (
	"context"
	"flag"
	"fmt"
	"path/filepath"

	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
	"k8s.io/client-go/util/homedir"
	"gitee.com/openfuyao/computing-power-engine/api/v1"
)

func main() {
	var kubeconfig string
	if home := homedir.HomeDir(); home != "" {
		flag.StringVar(&kubeconfig, "kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
	} else {
		flag.StringVar(&kubeconfig, "kubeconfig", "", "absolute path to the kubeconfig file")
	}
	deploymentName := flag.String("deployment-name", "", "name of the deployment to get and update")
	deploymentNamespace := flag.String("deployment-namespace", "default", "namespace of the deployment to get and update")
	flag.Parse()

	if *deploymentName == "" {
		fmt.Println("Please provide a deployment name with the --deployment-name flag")
		return
	}

	// 使用kubeconfig文件创建clientset
	config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
	if err != nil {
		panic(err.Error())
	}

	// 创建clientset
	clientset, err := kubernetes.NewForConfig(config)
	if err != nil {
		panic(err.Error())
	}

	// 获取Deployments的clientset
	deploymentsClient := clientset.AppsV1().Deployments(*deploymentNamespace)

	// 获取Deployment
	deployment, err := deploymentsClient.Get(context.TODO(), *deploymentName, metav1.GetOptions{})
	if err != nil {
		panic(err.Error())
	}

	fmt.Printf("Current replicas count for Deployment %s/%s: %d\n", deployment.Namespace, deployment.Name, *deployment.Spec.Replicas)

	// 修改Deployment的Replicas值
	// 例如，我们将其增加到5
	if deployment.Spec.Replicas == nil {
		deployment.Spec.Replicas = new(int32)
	}
	*deployment.Spec.Replicas = 5

	// 更新Deployment
	updatedDeployment, err := deploymentsClient.Update(context.TODO(), deployment, metav1.UpdateOptions{})
	if err != nil {
		panic(err.Error())
	}

	fmt.Printf("Updated replicas count for Deployment %s/%s: %d\n", updatedDeployment.Namespace, updatedDeployment.Name, *updatedDeployment.Spec.Replicas)


	engine := v1.Engine{}
	engine.Name = "bolt"
	fmt.Printf("hello enginePlugin: %s\n", engine.Name)
}
